package com.common.util;

import java.io.*;
import java.math.BigInteger;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;

public class FileMD5 {

    /**
     * get file md5
     * @param file
     * @return
     * @throws NoSuchAlgorithmException
     * @throws IOException
     */
	public static String getFileMD5(File file) throws NoSuchAlgorithmException, IOException {
        if (!file.isFile()) {
            return null;
        }
        MessageDigest digest;
        FileInputStream in;
        byte buffer[] = new byte[1024];
        int len;
        digest = MessageDigest.getInstance("MD5");
        in = new FileInputStream(file);
        while ((len = in.read(buffer, 0, 1024)) != -1) {
            digest.update(buffer, 0, len);
        }
        in.close();
        BigInteger bigInt = new BigInteger(1, digest.digest());
        return bigInt.toString(16);
    }


    public static String getFileMd5(String filePath) {
        URL url = null;
        String urlString = "";
        try {
            MessageDigest digest;
            url = new URL(filePath);
            URLConnection conn = url.openConnection();
//            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            InputStream in = new BufferedInputStream(conn.getInputStream());
            int len;
            byte buffer[] = new byte[1024];
            digest = MessageDigest.getInstance("MD5");
            while ((len = in.read(buffer, 0, 1024)) != -1) {
                digest.update(buffer, 0, len);
            }
            in.close();
            BigInteger bigInt = new BigInteger(1, digest.digest());
            return bigInt.toString(16);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return urlString;
    }


    /**
     * 对广告文件进行重命名
     * @param oldName 原名
     * @return 新的文件名
     */
    public String reName(String oldName) {
        return MD5Util.str2md5(System.currentTimeMillis() + oldName) + "." +
                oldName.substring(oldName.lastIndexOf(".") + 1, oldName.length());
    }


//    public static void main(String[] args) throws IOException, NoSuchAlgorithmException {
//        File file = new File("D:\\mnt\\nfs_data\\firmware\\3288E\\SDK\\update_V9.9.9.9_20190903.zip");
//        String fileMD5 = FileMD5.getFileMD5(file);
//        System.out.println(fileMD5);
//    }


//    public static void main(String[] args) {
//        String md5 = FileUtils.getFileMd5("http://129.204.64.118:88/ostmsAdv/firmware/MD5/" + "3288U/SDK" + "/firmware.txt");
//        System.out.println(md5);
//    }
}
